package com.gu.reentrantLock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: gusongliao
 * @Description: 演示可重入锁
 * @createDate 2023/05/27 18:32
 */
public class LockLockDemo6_3_1 {

    public synchronized void add() {
        add();
    }

    public static void main(String[] args) {

        Lock lock = new ReentrantLock();

        // synchronized
        /**  输出效果如下
         * t1 外层
         * t1 中层
         * t1 内层
         *
         * 未输出 新建线程 并且main方法不能正常结束
         *
         * 分析如下 第一个线程存在未解锁的情况，导致下方获取不到锁
         */
        Object o = new Object();
        new Thread(() -> {

            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName() + " 外层");

                try {
                    lock.lock();
                    System.out.println(Thread.currentThread().getName() + " 中层");

                    try {
                        lock.lock();
                        System.out.println(Thread.currentThread().getName() + " 内层");
                    } finally {
                        // 未解锁
                        //lock.unlock();
                    }
                } finally {
                    lock.unlock();
                }
            } finally {

                 lock.unlock();
            }

        }, "t1").start();

        new Thread(() -> {
            lock.lock();
            System.out.println("新建线程");
            lock.unlock();
        },"BB").start();

    }

}
